package com.hencoderplus.demo1;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;

/**
 * hencoderplus
 * Created by lzw on 2018/10/26. 16:07:40
 * 邮箱：632393724@qq.com
 * All Rights Saved! Chongqing AnYun Tech co. LTD
 */
public class ImageTextView extends View {

    Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
    private static final int IMAGE_WIDTH = (int) Utils.dp2Px(50);
    private static final int left = 100;
    Paint.FontMetrics fontMetrics = new Paint.FontMetrics();
    private static final int IMAGE_OFFSET = (int) Utils.dp2Px(50);

    Bitmap bitmap = null;
    String drawText = "Mesa CI是Intel的一个持续集成系统，用于运行Mesa图形库的构建和一致性测试套件。它运行在200多个系统中，每天运行数千万次测试" +
            "如今网络购物已经非常普及，各种打折促销也是商家营销的重要手段。可是如果您遇到虚假促销该怎么办呢？是忍忍算了，还是拿起法律武器维权呢？日前，家住广州的郑先生在天猫超市购物时就遭到了虚假宣传，他是如何维权的呢";
    private float maxWidth;
    private float[] cutwidth = new float[1];

    {
        bitmap = Utils.decodeBitmap(getContext(), IMAGE_WIDTH);
        paint.setTextSize(Utils.dp2Px(14));
        fontMetrics = paint.getFontMetrics();
    }

    public ImageTextView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.drawBitmap(bitmap,getWidth()-IMAGE_WIDTH, IMAGE_OFFSET,paint);
        int length = drawText.length();
        float verticalOffset =  -fontMetrics.top;


        for (int start = 0; start < length; ) {
            int maxWidth ;
            // Top指的是指的是最高字符到baseline的值，即ascent的最大值
            float textTop = verticalOffset + fontMetrics.top;
            //bottom指的是最下字符到baseline的值，即descent的最大值
            float textBottom = verticalOffset + fontMetrics.bottom;
            if (textTop> IMAGE_OFFSET && textTop< IMAGE_OFFSET +IMAGE_WIDTH ||
                    (textBottom> IMAGE_OFFSET && textBottom< IMAGE_OFFSET +IMAGE_WIDTH)){
                //文字和图片处在同一行
                maxWidth = getWidth()-IMAGE_WIDTH;
            }else{
                maxWidth = getWidth();
            }
            int count = paint.breakText(drawText,start,length,true,maxWidth,cutwidth);
            canvas.drawText(drawText,start,start+count,0,verticalOffset,paint);
            start+=count;
            verticalOffset+= paint.getFontSpacing();
        }

    }
}
